using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace SmartLink.Infrastructure
{
    public class HttpHelper
    {
        /// <summary>
        /// 发送注册短信
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string SendRegisterMessage(string phoneNumber, string code)
        {
            return SendMessage(phoneNumber, "17638", "#code#=" + code);
        }

        #region 检查关键字
        public static string CheckWord(string word)
        {
            string appkey = "bcd5c0ae07d8dfa5d3e4173666575e33"; //配置您申请的appkey
            //1.屏蔽词检查测
            string url = "http://v.juhe.cn/sms/black";

            var parameters = new Dictionary<string, string>();

            parameters.Add("word", word); //需要检测的短信内容，需要UTF8 URLENCODE
            parameters.Add("key", appkey);//你申请的key

            string result = sendPost(url, parameters, "get");
            string msg = string.Empty;
            try
            {
                dynamic newObj = JsonEx.DeserializeObject(result,typeof(object));
                String errorCode = newObj["error_code"].Value;
                if (newObj["error_code"] == null)
                {
                    return string.Empty;
                }

                if (errorCode == "0")
                {
                   // Common.Helper.UtilHelper.WriteLog(null, newObj.ToString(), "Api");
                }
                else
                {
                    msg = newObj["reason"].Value;
                }
            }
            catch (Exception e)
            {
                msg = "短信发送失败,请稍后再试";
            }
            return msg;
        }
        #endregion

        #region 发送短信
        public static string SendMessage(string phoneNumber, string tpl_id, string tpl_value)
        {
            string appkey = "bcd5c0ae07d8dfa5d3e4173666575e33";
            //2.发送短信
            string url = "http://v.juhe.cn/sms/send";

            var parameters = new Dictionary<string, string>();

            parameters.Add("mobile", phoneNumber); //接收短信的手机号码
            parameters.Add("tpl_id", tpl_id); //短信模板ID，请参考个人中心短信模板设置
            parameters.Add("tpl_value", HttpUtility.UrlEncode(tpl_value, System.Text.UTF8Encoding.UTF8)); //变量名和变量值对。如果你的变量名或者变量值中带有#&amp;=中的任意一个特殊符号，请先分别进行urlencode编码后再传递，&lt;a href=&quot;http://www.juhe.cn/news/index/id/50&quot; target=&quot;_blank&quot;&gt;详细说明&gt;&lt;/a&gt;
            parameters.Add("key", appkey);//你申请的key
            parameters.Add("dtype", "json"); //返回数据的格式,xml或json，默认json

            string result = sendPost(url, parameters, "get");
            string msg = string.Empty;
            try
            {
                var newObj = JsonConvert.DeserializeObject<dynamic>(result);
                if (newObj["error_code"] == null)
                {
                    return string.Empty;
                }
                Newtonsoft.Json.Linq.JValue jValue =(Newtonsoft.Json.Linq.JValue)(newObj["error_code"]);
                string errorCode = jValue.Value.ToString();
                //String errorCode = newObj["error_code"].Value;
                if (errorCode == "0")
                {
                   // Common.Helper.UtilHelper.WriteLog(null, newObj.ToString(), "Api");
                }
                else
                {
                    msg = newObj["reason"].Value;
                }
            }
            catch (Exception e)
            {
                msg = "短信发送失败,请稍后再试";
            }
            return msg;
        }
        #endregion

        #region 发送请求调用api

        /// <summary>
        /// Http (GET/POST)
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="method">请求方法</param>
        /// <returns>响应内容</returns>
        public static string sendPost(string url, IDictionary<string, string> parameters, string method)
        {
            if (method.ToLower() == "post")
            {
                HttpWebRequest req = null;
                HttpWebResponse rsp = null;
                System.IO.Stream reqStream = null;
                try
                {
                    req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = method;
                    req.KeepAlive = false;
                    req.ProtocolVersion = HttpVersion.Version10;
                    req.Timeout = 5000;
                    req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                    byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
                    reqStream = req.GetRequestStream();
                    reqStream.Write(postData, 0, postData.Length);
                    rsp = (HttpWebResponse)req.GetResponse();
                    Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                    return GetResponseAsString(rsp, encoding);
                }
                catch (Exception ex)
                {
                    return "{" + ex.Message + "}";
                }
                finally
                {
                    if (reqStream != null) reqStream.Close();
                    if (rsp != null) rsp.Close();
                }
            }
            else
            {
                //创建请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));

                //GET请求
                request.Method = "GET";
                request.ReadWriteTimeout = 5000;
                request.ContentType = "text/html;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));

                //返回内容
                string retString = myStreamReader.ReadToEnd();
                return retString;
            }
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        protected static string BuildQuery(IDictionary<string, string> parameters, string encode)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            if (parameters == null)
                return string.Empty;
            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(name);
                    postData.Append("=");
                    if (encode == "gb2312")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                    }
                    else if (encode == "utf8")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    }
                    else
                    {
                        postData.Append(value);
                    }
                    hasParam = true;
                }
            }
            return postData.ToString();
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        protected static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }

        #endregion


        public static byte[] HttpDownloadFile(string url)
        {
            string Cookie = String.Empty;
            String refer = url.Substring(0, url.LastIndexOf("/") + 1);
            System.Net.HttpWebRequest req = System.Net.HttpWebRequest.Create(url) as System.Net.HttpWebRequest;
            req.AllowAutoRedirect = false;
            req.Referer = refer;
            req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
            System.Net.HttpWebResponse res = req.GetResponse() as System.Net.HttpWebResponse;
            System.Net.WebHeaderCollection headers = res.Headers;
            String newUrl = "";
            if ((res.StatusCode == System.Net.HttpStatusCode.Found) ||
            (res.StatusCode == System.Net.HttpStatusCode.Redirect) ||
            (res.StatusCode == System.Net.HttpStatusCode.Moved) ||
            (res.StatusCode == System.Net.HttpStatusCode.MovedPermanently))
            {
                newUrl = headers["Location"];
                newUrl = newUrl.Trim();
            }
            if (headers["Set-Cookie"] != null)
            {
                Cookie = headers["Set-Cookie"];
            }
            NameValueCollection collHeader = new NameValueCollection();
            if (Cookie.Length > 0)
            {
                collHeader.Add("Cookie", Cookie);
            }
            res.Close();
            req = null;
            String fileName = newUrl.Substring(newUrl.LastIndexOf("/") + 1);
            req = System.Net.HttpWebRequest.Create(newUrl) as System.Net.HttpWebRequest;
            req.AllowAutoRedirect = true;
            req.Referer = url;
            req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
            res = req.GetResponse() as System.Net.HttpWebResponse;
            System.IO.Stream stream = res.GetResponseStream();
            byte[] buffer = new byte[32 * 1024];
            int bytesProcessed = 0;
            byte[] allbytes = new byte[res.ContentLength];
            int bytesRead;
            do
            {
                bytesRead = stream.Read(buffer, 0, buffer.Length);
                Array.Copy(buffer, 0, allbytes, bytesProcessed, bytesRead);
                bytesProcessed += bytesRead;
            }
            while (bytesRead > 0);
            res.Close();
            return allbytes;
        }
    }
}